//
//  VideoManagerCenter.m
//  安好
//
//  Created by qinlongqing on 15/1/6.
//  Copyright (c) 2015年 lianchuangbrother. All rights reserved.
//

#import "VideoManagerCenter.h"
#import "AnyChatDefine.h"
#import "AnyChatErrorCode.h"
#import "AnyChatPlatform.h"
#import "VideoViewController.h"
#import "VideoSettingViewController.h"
#import "VideoListViewController.h"
#import "VideoUserEntity.h"
#import "OnlineChatVideoWindow.h"

static NSString *specifierString = @"&&%%&&**##@@";

static VideoManagerCenter *instance = nil;


@interface VideoManagerCenter ()<AnyChatNotifyMessageDelegate,AnyChatVideoCallDelegate>
{
    AnyChatPlatform *anyChat;

    BOOL theOnLineLoginState;//在线状态

    UIAlertView *theReplyAlertView;//同一个房间请求进行会话弹出的alertVeiw，可以拒绝和同意
    UIAlertView *theWaitingAlertView;//等待界面
    
    AVAudioPlayer *theAudioPlayer;
}
@end

@implementation VideoManagerCenter

- (instancetype)init{
    self = [super init];
    if (self) {
        
    }
    return self;
}

+ (VideoManagerCenter *)instance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
        
        [instance setup];
        
        [instance initWithCallSound];
    });
    return instance;
}

- (void)setup{
    _userOnlineArray = [[NSMutableArray alloc]init];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(AnyChatNotifyHandler:) name:@"ANYCHATNOTIFY" object:nil];
    
    [AnyChatPlatform InitSDK:0];
    
    anyChat = [[AnyChatPlatform alloc]init];
    anyChat.notifyMsgDelegate = self;
//    anyChat.textMsgDelegate = self;
//    anyChat.transDataDelegate = self;
//    anyChat.recordSnapShotDelegate = self;
    anyChat.videoCallDelegate = self;
    
    [AnyChatPlatform UserInfoControl:-1 :BRAC_USERINFO_CTRLCODE_DEBUGLOG :5 :1 :@""];
    
    [self doLogin];

}

- (void)initWithCallSound{
    NSString *musicPath = [[NSBundle mainBundle] pathForResource:@"sound_phoneCall" ofType:@"caf"];
    if (musicPath){
        NSURL *musicURL = [NSURL fileURLWithPath:musicPath];
        theAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:musicURL error:nil];
        theAudioPlayer.numberOfLoops = -1;
    }
}

- (void)stopAudioPlayer{
    [theAudioPlayer stop];
}

#pragma mark - Instance Method
- (void)AnyChatNotifyHandler:(NSNotification*)notify{
    NSDictionary* dict = notify.userInfo;
    [anyChat OnRecvAnyChatNotify:dict];
}

//登录
- (void)doLogin{
    if (theOnLineLoginState == NO) {
        [AnyChatPlatform Connect:[self getServerIP] :[[self getServerPort] integerValue]];// 连接服务器
        
        [AnyChatPlatform Login:[self combinationCurrentUserName] :@""];
    }
}

//退出登录
- (void)doLogout{
    [[OnlineChatVideoWindow shared] stopChatView];
    if (theOnLineLoginState == YES) {
        [AnyChatPlatform Logout];
        theOnLineLoginState = NO;
    }
}

- (NSString *)combinationCurrentUserName{//组装用户名
    return [NSString stringWithFormat:@"%@%@%@%@user%@%@",[[UserManager shareInstance] getUserInfo].realname,specifierString,[[UserManager shareInstance] getUserInfo].uid,specifierString,specifierString,isUserOnLine];
}
- (NSString *)parsingCurrentUserNameToGetUserName:(NSString *)userName{//解析用户名
    NSArray *specifierArray = [userName componentsSeparatedByString:specifierString];
    if (specifierArray.count > 0) {
        return [specifierArray objectAtIndex:0];
    }
    return nil;
}
- (NSString *)parsingCurrentUserNameToGetUserID:(NSString *)userName{//解析用户名
    NSArray *specifierArray = [userName componentsSeparatedByString:specifierString];
    if (specifierArray.count > 1) {
        return [specifierArray objectAtIndex:1];
    }
    return nil;
}
- (NSString *)parsingCurrentUserNameToGetRole:(NSString *)userName{//解析用户名
    NSArray *specifierArray = [userName componentsSeparatedByString:specifierString];
    if (specifierArray.count > 2) {
        return [specifierArray objectAtIndex:2];
    }
    return nil;
}
- (NSString *)parsingCurrentUserNameToGetIsOnLine:(NSString *)userName{//解析用户名
    NSArray *specifierArray = [userName componentsSeparatedByString:specifierString];
    if (specifierArray.count > 3) {
        return [specifierArray objectAtIndex:3];
    }
    return nil;
}



- (NSString *)getServerIP{
    NSString *serverIP;
    NSString *userSettingPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"onlineUserSetting.plist"];
    if ([[NSFileManager defaultManager] fileExistsAtPath:userSettingPath]) {
        NSMutableArray *array = [[NSMutableArray alloc]initWithContentsOfFile:userSettingPath];
        serverIP = [array objectAtIndex:0];
        if ([serverIP length]==0) {
            serverIP = @"demo.anychat.cn";
//            serverIP = @"114.215.196.126";
        }
    }
    else{
        serverIP = @"demo.anychat.cn";
//        serverIP = @"114.215.196.126";
    }
    return serverIP;
}

- (NSString *)getServerPort{
    NSString *serverPort;
    NSString *userSettingPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"onlineUserSetting.plist"];
    if ([[NSFileManager defaultManager] fileExistsAtPath:userSettingPath]) {
        NSMutableArray *array = [[NSMutableArray alloc]initWithContentsOfFile:userSettingPath];
        serverPort = [array objectAtIndex:1];
        
        if ([serverPort integerValue] == 0 || [serverPort length] == 0) {
            serverPort = @"8906";
        }
    }
    else{
        serverPort = @"8906";
    }
    return serverPort;
}

- (NSString *)getRoomNumber{
    NSString *roomNumber;
    NSString *userSettingPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"onlineUserSetting.plist"];
    if ([[NSFileManager defaultManager] fileExistsAtPath:userSettingPath]) {
        NSMutableArray *array = [[NSMutableArray alloc]initWithContentsOfFile:userSettingPath];
        roomNumber = [array objectAtIndex:2];
        
        if ([roomNumber integerValue] == 0 || [roomNumber length] == 0) {
            roomNumber = @"99999";
        }
    }
    else{
        roomNumber = @"99999";
    }
    return roomNumber;
}

#pragma AnyChatNotifyMessageDelegate
- (void)OnAnyChatConnect:(BOOL)bSuccess{//链接服务器成功
    
}

- (void)OnAnyChatLogin:(int)dwUserId :(int)dwErrorCode{//登录服务器成功
    if (dwErrorCode == GV_ERR_SUCCESS) {
        theOnLineLoginState = YES;
        _myUserID = dwUserId;
        _myUserName = [[UserManager shareInstance] getUserInfo].username;
        [AnyChatPlatform EnterRoom:[[self getRoomNumber] integerValue] :@""];
    }
    else{
        theOnLineLoginState = NO;
    }
}

- (void)OnAnyChatEnterRoom:(int)dwRoomId :(int)dwErrorCode{//进入某个房间
//    [[VideoSettingViewController instance] updateUserVideoSettings];
    
    [self getAndStoreAllOnlineUserInfo];
    
    [[VideoListViewController instance].userOnLineListTableView reloadData];
}

// 房间在线用户消息
- (void)OnAnyChatOnlineUser:(int)dwUserNum :(int)dwRoomId{
    [self getAndStoreAllOnlineUserInfo];
}

// 用户进入房间消息
- (void)OnAnyChatUserEnterRoom:(int)dwUserId{
    [self getAndStoreAllOnlineUserInfo];
}

// 用户退出房间消息
- (void)OnAnyChatUserLeaveRoom:(int)dwUserId{
    if ([OnlineChatVideoWindow shared].videoViewController.iRemoteUserId == dwUserId) {//远程聊天的用户离线
        [[OnlineChatVideoWindow shared].videoViewController FinishVideoChat];
        [OnlineChatVideoWindow shared].videoViewController.iRemoteUserId = -1;
        [[OnlineChatVideoWindow shared] stopChatView];//结束视频聊天
    }
    [self getAndStoreAllOnlineUserInfo];
}

// 网络断开消息
- (void)OnAnyChatLinkClose:(int)dwErrorCode{
    [[OnlineChatVideoWindow shared].videoViewController FinishVideoChat];
    [AnyChatPlatform LeaveRoom:-1];
    [AnyChatPlatform Logout];
    theOnLineLoginState = NO;
    
    [_userOnlineArray removeAllObjects];
    [[VideoListViewController instance].userOnLineListTableView reloadData];
    
    [[OnlineChatVideoWindow shared] stopChatView];//结束视频聊天
}


- (void)getAndStoreAllOnlineUserInfo{
    [_userOnlineArray removeAllObjects];
    NSMutableArray *allOnLineUser = [AnyChatPlatform GetOnlineUser];
    
    for (NSInteger i=0; i<allOnLineUser.count; i++) {
        NSInteger userIDonAnyChat = [[allOnLineUser objectAtIndex:i] integerValue];
        NSString *userNameOnAnyChat = [AnyChatPlatform GetUserName:userIDonAnyChat];
        if ([[self parsingCurrentUserNameToGetRole:userNameOnAnyChat] isEqualToString:@"doctor"] && [[self parsingCurrentUserNameToGetIsOnLine:userNameOnAnyChat] isEqualToString:isUserOnLine]) {
            VideoUserEntity *entity = [[VideoUserEntity alloc]init];
            entity.userIDonAnyChat = userIDonAnyChat;
            entity.userID = [[self parsingCurrentUserNameToGetUserID:userNameOnAnyChat] integerValue];
            entity.userName = [self parsingCurrentUserNameToGetUserName:userNameOnAnyChat];
            [_userOnlineArray addObject:entity];
        }
    }
    [[VideoListViewController instance].userOnLineListTableView reloadData];
}

#pragma AnyChatVideoCallDelegate
- (void)OnAnyChatVideoCallEventCallBack:(int)dwEventType :(int)dwUserId :(int)dwErrorCode :(int)dwFlags :(int)dwParam :(NSString *)lpUserStr{
    _remoteUserID = dwUserId;
    _remoteUserName = [self parsingCurrentUserNameToGetUserName:[AnyChatPlatform GetUserName:_remoteUserID]];
    NSLog(@"********=%d",self.remoteUserID);
    switch (dwEventType) {
        case BRAC_VIDEOCALL_EVENT_REQUEST://呼叫请求
        {
            [self showReplyAlertView];//显示有远程的视频请求
            break;
        }
        case BRAC_VIDEOCALL_EVENT_REPLY://呼叫请求回复J
        {
            NSLog(@"BRAC_VIDEOCALL_EVENT_REPLY remoteUserID = %d  dwErrorCode = %d",self.remoteUserID,dwErrorCode);
            switch (dwErrorCode) {
                    self.isOnlineChat=NO;
                case GV_ERR_VIDEOCALL_CANCEL://远程用户取消会话
                {
                    [self dimissAlertView:theReplyAlertView];
                    [self showInfoAlertView:@"用户取消会话" :@"CANCEL"];
                    [theAudioPlayer stop];
                    [[OnlineChatVideoWindow shared] stopChatView];//用户网络不好或短线取消视频聊天
                    break;
                }
                case GV_ERR_VIDEOCALL_REJECT://目标用户拒绝会话
                {
                    if (theWaitingAlertView != nil) {
                        [self dimissAlertView:theWaitingAlertView];
                    }
                    [self showInfoAlertView:@"用户拒绝会话" :@"REJECT"];
                    [theAudioPlayer stop];
                    [[OnlineChatVideoWindow shared] stopChatView];//用户网络不好或短线取消视频聊天
                    break;
                }
                case GV_ERR_VIDEOCALL_OFFLINE://目标用户不在线
                {
                    if (theWaitingAlertView != nil) {
                        [self dimissAlertView:theWaitingAlertView];
                    }
                    [self showInfoAlertView:@"对方不在线" :@"OFFLINE"];
                    [theAudioPlayer stop];
                    [[OnlineChatVideoWindow shared] stopChatView];//用户网络不好或短线取消视频聊天
                    break;
                }
                case GV_ERR_VIDEOCALL_BUSY://目标用户忙
                {
                    if (theWaitingAlertView != nil) {
                        [self dimissAlertView:theWaitingAlertView];
                    }
                    [self showInfoAlertView:@"用户在忙" :@"BUSY"];
                    [theAudioPlayer stop];
                    [[OnlineChatVideoWindow shared] stopChatView];//用户网络不好或短线取消视频聊天
                    break;
                }
                case GV_ERR_VIDEOCALL_TIMEOUT://会话请求超时
                {
                    if (theWaitingAlertView != nil)
                    {
                        [self dimissAlertView:theWaitingAlertView];
                    }
                    [self showInfoAlertView:@"会话请求超时" :@"TIMEOUT"];
                    [theAudioPlayer stop];
                    [[OnlineChatVideoWindow shared] stopChatView];//用户网络不好或短线取消视频聊天
                    break;
                }
                case GV_ERR_VIDEOCALL_DISCONNECT://网络断线
                {
                    if (theWaitingAlertView != nil)
                    {
                        [self dimissAlertView:theWaitingAlertView];
                    }
                    [self showInfoAlertView:@"网络断线" :@"DISCONNECT"];
                    [theAudioPlayer stop];
                    [[OnlineChatVideoWindow shared] stopChatView];//用户网络不好或短线取消视频聊天
                    break;
                }
                    
                case GV_ERR_VIDEOCALL_NOTINCALL://用户不在呼叫状态
                {
                    if (theWaitingAlertView != nil)
                    {
                        [self dimissAlertView:theWaitingAlertView];
                    }
                    [self showInfoAlertView:@"用户不在呼叫状态" :@"NOTINCALL"];
                    [theAudioPlayer stop];
                    [[OnlineChatVideoWindow shared] stopChatView];//用户网络不好或短线取消视频聊天
                    break;
                }
            }
            break;
        }
            
        case BRAC_VIDEOCALL_EVENT_START://视频呼叫会话开始事件
        {
            NSLog(@"BRAC_VIDEOCALL_EVENT_START remoteUserID = %d",self.remoteUserID);

            [theAudioPlayer stop];
            if (theWaitingAlertView != nil) {
                [self dimissAlertView:theWaitingAlertView];
            }
//            [[OnlineChatVideoWindow shared] startChatView];//显示聊天界面、只有对方同意后(走BRAC_VIDEOCALL_EVENT_START代理回调后)才显示对方的头像

            [OnlineChatVideoWindow shared].videoViewController.iRemoteUserId = _remoteUserID;
            [[OnlineChatVideoWindow shared].videoViewController initAndStartVideoChat];//真正的开始开始视频聊天，有头像
            break;
        }
            
        case BRAC_VIDEOCALL_EVENT_FINISH://挂断（结束）呼叫会话
        {
            NSLog(@"BRAC_VIDEOCALL_EVENT_FINISH remoteUserID = %d",self.remoteUserID);

            [[OnlineChatVideoWindow shared].videoViewController FinishVideoChat];
            
//            [self showInfoAlertView:@"会话结束!" :@"Finish"];
            self.isOnlineChat=NO;
            [[OnlineChatVideoWindow shared] stopChatView];//结束视频聊天

            break;
        }
            
    }
    
}

- (void)showReplyAlertView{
    theReplyAlertView = [[UIAlertView alloc] initWithTitle:@"用户请求会话"
                                                   message:@"Video Call"
                                                  delegate:self
                                         cancelButtonTitle:@"拒绝"
                                         otherButtonTitles:@"同意", nil];
    [theReplyAlertView show];
    [theAudioPlayer play];
}

- (void)showWaitingAlertView{
    theWaitingAlertView = [[UIAlertView alloc] initWithTitle:@"用户取消会话"
                                                     message:@"Video Call"
                                                    delegate:self
                                           cancelButtonTitle:@"确定"
                                           otherButtonTitles:nil, nil];
    [theWaitingAlertView show];
}

- (NSString *)showInfoAlertView:(NSString *)titleCN : (NSString *)titleEN{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:titleCN
                                                        message:titleEN
                                                       delegate:self
                                              cancelButtonTitle:nil
                                              otherButtonTitles:nil,nil];
    [alertView show];
    
    [self performSelector:@selector(dimissAlertView:) withObject:alertView afterDelay:1.5];
    
    
    return titleEN;
}

- (void) dimissAlertView:(UIAlertView *)alert {
    if(alert){
        [alert dismissWithClickedButtonIndex:[alert cancelButtonIndex] animated:YES];
    }
}

#pragma UIAlertView Delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView == theReplyAlertView) {
        switch (buttonIndex) {
            case 0:
            {
                [AnyChatPlatform VideoCallControl:BRAC_VIDEOCALL_EVENT_REPLY :_remoteUserID :GV_ERR_VIDEOCALL_REJECT :0 :0 :nil];//在视频请求回复过程中拒绝视频请求
                [theAudioPlayer stop];
                break;
            }
            case 1:
            {
                NSLog(@"alertViewDelegate remoteUserID = %d",self.remoteUserID);
                [AnyChatPlatform VideoCallControl:BRAC_VIDEOCALL_EVENT_REPLY :_remoteUserID :0 :0 :0 :nil];
                [theAudioPlayer stop];
                break;
            }
        }
    }
    if (alertView == theWaitingAlertView) {
        if (buttonIndex == 0) {
            [AnyChatPlatform VideoCallControl:BRAC_VIDEOCALL_EVENT_REPLY :_remoteUserID :GV_ERR_VIDEOCALL_CANCEL :0 :0 :nil];//在视频请求回复过程中取消视频请求
            [self dimissAlertView:theWaitingAlertView];
            [theAudioPlayer stop];
        }
    }
}

- (void)startVideoChat{
    self.isOnlineChat=YES;
    _remoteUserID = [VideoListViewController instance].selectUserID;
    _remoteUserName = [self parsingCurrentUserNameToGetUserName:[AnyChatPlatform GetUserName:_remoteUserID]];
    [AnyChatPlatform VideoCallControl:BRAC_VIDEOCALL_EVENT_REQUEST :_remoteUserID :0 :0 :0 :nil];//呼叫
    [[OnlineChatVideoWindow shared] startChatView];
//    [[OnlineChatVideoWindow shared].videoViewController initAndStartVideoChat];//真正的开始开始视频聊天，有头像

    [theAudioPlayer play];
}

@end
